package com.hamilton.erik.pt.mobile.android;

import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import com.android.volley.Response;
import com.hamilton.erik.pt.mobile.android.volley.response.error.listener.DisplayErrorErrorListener;
import com.hamilton.erik.pt.mobile.client.VolleyJsonRestClient;
import com.hamilton.erik.pt.mobile.util.ServerUtil;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Activity which displays a register screen to the user, offering registration as
 * well.
 */
public class RegisterActivity extends Activity {

	/**
	 * Keep track of the register task to ensure we can cancel it if requested.
	 */

	// Values for email and password at the time of the register attempt.
	private String mUserName;
	private String mPassword;
	private String mValidatePassword;

	// UI references.
	private EditText mUserNameView;
	private EditText mPasswordView;
	private EditText mValidatePasswordView;
	private View mRegisterFormView;
	private View mRegisterStatusView;
	private TextView mRegisterStatusMessageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_register);

		// Set up the register form.
		mUserName = getIntent().getStringExtra(getString(R.string.extra_user_name));
		mUserNameView = (EditText) findViewById(R.id.register_userName);
		mUserNameView.setText(mUserName);

		mPasswordView = (EditText) findViewById(R.id.register_password);
		
		mValidatePasswordView = (EditText) findViewById(R.id.register_validate_password);
		mValidatePasswordView
			.setOnEditorActionListener(new TextView.OnEditorActionListener() {
				@Override
				public boolean onEditorAction(TextView textView, int id,
						KeyEvent keyEvent) {
					if (id == R.id.register || id == EditorInfo.IME_NULL) {
						attemptRegister();
						return true;
					}
					return false;
				}
			});

		mRegisterFormView = findViewById(R.id.register_form);
		mRegisterStatusView = findViewById(R.id.register_status);
		mRegisterStatusMessageView = (TextView) findViewById(R.id.register_status_message);

		findViewById(R.id.register_register_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptRegister();
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.register, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the register form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual register attempt is made.
	 */
	@SuppressLint("DefaultLocale")
	public void attemptRegister() {
		
		// Reset errors.
		mUserNameView.setError(null);
		mPasswordView.setError(null);
		mValidatePasswordView.setError(null);

		// Store values at the time of the register attempt.
		mUserName = mUserNameView.getText().toString().trim().toLowerCase();
		mPassword = mPasswordView.getText().toString().trim();
		mValidatePassword = mValidatePasswordView.getText().toString().trim();

		boolean cancel = false;
		View focusView = null;



		// Check for a valid user name
		if (TextUtils.isEmpty(mUserName)) {
			mUserNameView.setError(getString(R.string.error_field_required));
			focusView = mUserNameView;
			cancel = true;
		}
		else if (mUserName.length() < 6 || mUserName.length() > 36) {	// Length between be 6 and 36
			mUserNameView.setError(getString(R.string.error_username_length));
			focusView = mUserNameView;
			cancel = true;
		} 
		else if(!mUserName.matches("^[a-zA-Z0-9]*$")) { // Only alphanumeric characters
			mUserNameView.setError(getString(R.string.error_field_alphanumeric_only));
			focusView = mUserNameView;
			cancel = true;
		}
		else if(mUserName.matches(".*\\s.*"))	{	// Contains no spacing
			mUserNameView.setError(getString(R.string.error_field_no_spaces));
			focusView = mUserNameView;
			cancel = true;
		}
		
		// Check for a valid password
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		}
		else if (mPassword.length() < 6) {	// Min length must be 6
			mPasswordView.setError(getString(R.string.error_password_too_short));
			focusView = mPasswordView;
			cancel = true;
		}
		else if(!mPassword.matches(".*\\d.*")) {	// Contains numbers
			mPasswordView.setError(getString(R.string.error_password_numbers_required));
			focusView = mPasswordView;
			cancel = true;
		}
		else if(!mPassword.matches(".*[a-zA-Z].*")) {	// Contains letters
			mPasswordView.setError(getString(R.string.error_password_chars_required));
			focusView = mPasswordView;
			cancel = true;
		} 
		else if(!mPassword.matches("^[a-zA-Z0-9]*$")) { // Only alphanumeric characters
			mPasswordView.setError(getString(R.string.error_field_alphanumeric_only));
			focusView = mPasswordView;
			cancel = true;
		}
		else if(mPassword.matches(".*\\s.*"))	{	// Contains no spacing
			mPasswordView.setError(getString(R.string.error_field_no_spaces));
			focusView = mPasswordView;
			cancel = true;
		}
		
		// Check that the passwords match
		if (TextUtils.isEmpty(mValidatePassword)) {
			mValidatePasswordView.setError(getString(R.string.error_field_required));
			focusView = mValidatePasswordView;
			cancel = true;
		}
		else if(!mValidatePassword.equals(mPassword)) {
			mValidatePasswordView.setError(getString(R.string.error_non_matching_passwords));
			focusView = mValidatePasswordView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt register and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user register attempt.
			mRegisterStatusMessageView.setText(R.string.register_progress_registering);
			showProgress(true);
			
			StringBuilder url = new StringBuilder(ServerUtil.getInstance().buildAuthenticationPath());
			url.append("/register");
			
			Map<String, String> params = new HashMap<String, String>();
			params.put("userName", mUserName);
			params.put("password", mPassword);
			
			VolleyJsonRestClient.getClient()
					.postJsonObject(
							url.toString(),
							new RegisterSuccessListener(), 
							new DisplayErrorErrorListener(RegisterActivity.this),
							params);
		}
	}

	/**
	 * Shows the progress UI and hides the register form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mRegisterStatusView.setVisibility(View.VISIBLE);
			mRegisterStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mRegisterStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mRegisterFormView.setVisibility(View.VISIBLE);
			mRegisterFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mRegisterFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mRegisterStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mRegisterFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}
	
	/**
	 * Represents an asynchronous registration task used to register
	 * the user.
	 */
	private class RegisterSuccessListener implements Response.Listener<JSONObject> {

		@Override
		public void onResponse(JSONObject response) {
			Intent animalListActivity = new Intent(getApplicationContext(), AnimalListActivity.class);
			animalListActivity.putExtra(getString(R.string.extra_user_name), mUserName);
			startActivity(animalListActivity);
			
			// Finish the activity so the user can't navigate back to it
			finish();
		}
		
	}
}
